﻿using System.Runtime.InteropServices;

namespace breakoutsharp.utility
{
    public sealed class QueryPerfCounter
    {
        [DllImport("KERNEL32")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

        [DllImport("KERNEL32")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);

        private long frequency;
        private long stop = 0;
        private long start = 0;
        decimal multiplier = new decimal(1.0e9);

        public QueryPerfCounter()
        {
            if (QueryPerformanceFrequency(out frequency) == false)
            {
                // for some reason frequency was not supported
                throw new System.ComponentModel.Win32Exception();
            }

        }

        public void Start()
        {
            QueryPerformanceCounter(out start);
        }

        public void Stop()
        {
            if (start == 0 && stop == 0)
            {
                stop = 0;
                return;
            }

            QueryPerformanceCounter(out stop);
        }

        public double Duration(int iterations)
        {
            return ((((double)(stop-start)*
                (double) multiplier)/(double) frequency)/iterations);
        }

        public double DurationMilliseconds()
        {
            int iterations = 1;
            return ((((double)(stop - start) *
                      (double)multiplier) / (double)frequency) / iterations)/1000000;
        }

        public double DurationNanoseconds()
        {
            int iterations = 1;
            return ((((double)(stop - start) *
                      (double)multiplier) / (double)frequency) / iterations);
        }



    }
}
